package cn.iocoder.yudao.module.design.controller.admin.notes;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.design.controller.admin.notes.vo.*;
import cn.iocoder.yudao.module.design.convert.notes.NotesConvert;
import cn.iocoder.yudao.module.design.dal.dataobject.notes.NotesDO;
import cn.iocoder.yudao.module.design.service.notes.NotesService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;


@Tag(name = "管理后台 - 项目笔记")
@RestController
@RequestMapping("/design/notes")
@Validated
public class NotesController {

    @Resource
    private NotesService notesService;


    @Resource
    private AdminUserService userService;

    @PostMapping("/create")
    @Operation(summary ="创建项目笔记")
    @PreAuthorize("@ss.hasPermission('design:notes:create')")
    public CommonResult<Long> createNotes(@Valid @RequestBody NotesCreateReqVO createReqVO) {
        return success(notesService.createNotes(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary ="更新项目笔记")
    @PreAuthorize("@ss.hasPermission('design:notes:update')")
    public CommonResult<Boolean> updateNotes(@Valid @RequestBody NotesUpdateReqVO updateReqVO) {
        notesService.updateNotes(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary ="删除项目笔记")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('design:notes:delete')")
    public CommonResult<Boolean> deleteNotes(@RequestParam("id") Long id) {
        notesService.deleteNotes(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary ="获得项目笔记")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('design:notes:query')")
    public CommonResult<NotesRespVO> getNotes(@RequestParam("id") Long id) {
        NotesDO notes = notesService.getNotes(id);
        return success(NotesConvert.INSTANCE.convert(notes));
    }

    @GetMapping("/list")
    @Operation(summary ="获得项目笔记列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('design:notes:query')")
    public CommonResult<List<NotesRespVO>> getNotesList(@RequestParam("ids") Collection<Long> ids) {
        List<NotesDO> list = notesService.getNotesList(ids);
        return success(NotesConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary ="获得项目笔记分页")
    @PreAuthorize("@ss.hasPermission('design:notes:query')")
    public CommonResult<PageResult<NotesRespVO>> getNotesPage(@Valid NotesPageReqVO pageVO) {
       if(StrUtil.isNotEmpty(pageVO.getMonth())){
            // 计算当月第一天
           String monthStr = pageVO.getMonth()+"-01";
           // 计算当月第一天和最后一天
           Date firstDayOfMonth = DateUtil.beginOfMonth(DateUtil.parse(monthStr));
           Date lastDayOfMonth = DateUtil.endOfMonth(DateUtil.parse(monthStr));

           // 将结果放入Date[]数组对象
           Date[] dates = {firstDayOfMonth, lastDayOfMonth};
           pageVO.setCreateTime(dates);
       }

        PageResult<NotesDO> pageResult = notesService.getNotesPage(pageVO);

        // 获得拼接需要的数据
        Set<String> creatorIds = new HashSet<>(convertList(pageResult.getList(), NotesDO::getCreator));
        Set<Long> creatorIdsLong = creatorIds.stream()
                .map(Long::valueOf)
                .collect(Collectors.toSet());
        Map<Long, AdminUserDO> userMap = userService.getUserMap(creatorIdsLong);
        // 拼接结果返回
        List<NotesRespVO> respVOList = new ArrayList<>(pageResult.getList().size());
        pageResult.getList().forEach(user -> {
            NotesRespVO respVO = NotesConvert.INSTANCE.convert(user);
            respVO.setCreateName(userMap.get(Long.valueOf(user.getCreator() )).getNickname());
            respVOList.add(respVO);

        });

        return success(new PageResult<>(respVOList, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary ="导出项目笔记 Excel")
    @PreAuthorize("@ss.hasPermission('design:notes:export')")
   
    public void exportNotesExcel(@Valid NotesExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<NotesDO> list = notesService.getNotesList(exportReqVO);
        // 导出 Excel
        List<NotesExcelVO> datas = NotesConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "项目笔记.xls", "数据", NotesExcelVO.class, datas);
    }

}
